package com.woniu.carrent.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.carrent.mapper.TMenuMapper;
import com.woniu.carrent.pojo.TMenu;
import com.woniu.carrent.service.TMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TMenuServiceImpl extends ServiceImpl<TMenuMapper, TMenu> implements TMenuService {
    @Autowired
    private TMenuMapper tMenuMapper;
    @Override
    public List<TMenu> selectMenusByTypeId(Integer utypeid) {
        List<TMenu> menus0 = tMenuMapper.selectMenusByTypeId(0);
        List<TMenu> menus = tMenuMapper.selectMenusByTypeId(utypeid);
        menus.addAll(menus0);
        List<TMenu> resMenus = new ArrayList<>();

        for (TMenu menu : menus){
            if (menu.getLevel()==1){
               resMenus.add(menu);
            }
        }
        // 根据一级菜单找出对应子菜单
        for (TMenu menu : resMenus) {
            menu.setChildren(getChildren(menu.getMenuid(), menus));
        }
        return resMenus;

    }
    //递归
    private List<TMenu> getChildren(Integer parentId, List<TMenu> menus) {
        List<TMenu> children = new ArrayList<>();
        for (TMenu menu : menus) {
            if (menu.getParentid()==parentId) {
                children.add(menu);
            }
        }
        // 为每个子菜单也查找其子菜单
        for (TMenu childMenu : children) {
            childMenu.setChildren(getChildren(childMenu.getMenuid(), menus));
        }

        return children;
    }
}
